class ImgSprite {
  /**
   * @param width canvas的宽度
   * @param height canvas的高度
   * @param img 原始图片对象
   */
  constructor({ width, height, img }) {
    this.canvasWidth = width;    // canvas的宽度
    this.canvasHeight = height;  // canvas的高度
    this._img = img;  // image对象
    this.left = 0;   // 位移的x轴至
    this.top = 0;    // 位移的y轴值
    this.scale = 1;  // 缩放程度
    this.minScale = 1; // 允许的最小的缩放大小
    this.rotate = 0; // 旋转度数
    this.width = this._img.naturalWidth;  // 图片的原始宽度
    this.height = this._img.naturalHeight; // 图片的原始高度
  }

  /**
   * 获取弧度值
   * @returns {number}
   */
  get rotateRadian() {
    return this.rotate * Math.PI / 180;
  }

  get isVertical() {
    return (this.rotate / 90) % 2 === 1;
  }

  get actualWidth() {
    return this.isVertical ? this.height : this.width;
  }

  get actualHeight() {
    return this.isVertical ? this.width : this.height;
  }

  /**
   * 获取横向渲染的宽度是否超出canvas的范围
   * @returns {boolean}
   */
  get xOverflow() {
    return Math.round(this.actualWidth * this.scale - this.canvasWidth) > 0;
  }

  /**
   * 获取纵向渲染图片的高度是否超出canvas的范围
   * @returns {boolean}
   */
  get yOverflow() {
    return Math.round(this.actualHeight * this.scale - this.canvasHeight) > 0;
  }

  /**
   * 获取如果进行旋转，则需要对原点进行多少的位移
   * @returns {{top: number, left: *}|{top: *, left: number}|{top: *, left: *}|{top: number, left: number}}
   */
  get rotateTranslate() {
    const { left: leftBefore, top: topBefore, scale, width, height, rotate } = this;
    let left = leftBefore / scale;
    let top = topBefore / scale;
    if (rotate === 270) {
      top =  top + width;
    } else if (rotate === 180) {
      left = left + width;
      top = top + height;
    } else if (rotate === 90) {
      left = left + height;
    }
    return {
      left,
      top
    }
  }

  paint(ctx) {
    const { left, top } = this.rotateTranslate;
    const scale = this.scale;
    const overLimit = 10;
    ctx.clearRect(-overLimit, -overLimit, this.width + overLimit * 2, this.height + overLimit * 2);
    ctx.restore();
    ctx.save();
    // this.drawCenter('grey');
    ctx.translate(left * scale, top * scale);  // 平移到指定位置
    // this.drawCenter('green');
    ctx.rotate(this.rotateRadian); // 旋转画布
    ctx.scale(scale, scale); // 缩放画布
    // this.drawCenter('red');
    ctx.drawImage(this._img, 0, 0); // 画图
    // this.drawCenter('blue');
  }

  drawCenter(color, ctx) {
    ctx.beginPath();
    ctx.arc(0, 0, 20, 0, Math.PI*2, false);
    ctx.save();
    ctx.fillStyle = color;
    ctx.strokeStyle = '#ff0';
    ctx.stroke();
    ctx.fill();
    ctx.restore();
  }


}

